import mainEmail from '../config/Mailer'
import moment from 'moment'
import jwt from 'jsonwebtoken'
import bcryptjs from 'bcryptjs'
import config from '../config/'
import { checkCode, getJWTPayload } from '@/common/utils.js'
import UserModel from '../model/User'
import SignRecord from './../model/SignRecord'
import { v4 as uuidv4 } from 'uuid'
import { setValue, getValue, delValue } from '../config/RedisConfig'
class LoginController {
  async forget (ctx) {
    const { body } = ctx.request
    const check = await checkCode(body.sid, body.code)
    if (!check) {
      ctx.body = {
        code: 401,
        msg: '图形验证码不正确'
      }
      return
    }
    const key = uuidv4()
    const user = await UserModel.findOne({ username: body.username })
    if (!user) {
      ctx.body = {
        code: 404,
        msg: '该用户不存在'
      }
      return
    }
    const token = jwt.sign(
      {
        _id: user._id
      },
      config.JWT_SECRET,
      {
        expiresIn: 60 * 30
      }
    )
    setValue(key, token, 10 * 60)
    const res = await mainEmail({
      type: 'forget',
      data: {
        key
      },
      email: body.username,
      code: 1234,
      expire: moment().add(30, 'minutes').format('YYYY-MM-DD hh:mm:ss'),
      user: user.name
    })
    ctx.body = {
      data: res,
      code: 200,
      msg: 'success'
    }
  }

  async login (ctx) {
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    const username = body.username
    const password = body.password
    const check = await checkCode(sid, code)
    if (check) {
      const user = await UserModel.findOne({ username })
      if (user) {
        if (bcryptjs.compareSync(password, user.password)) {
          const token = jwt.sign(
            {
              _id: user._id
            },
            config.JWT_SECRET,
            {
              expiresIn: 60 * 60 * 24
            }
          )
          const userData = user.toJSON()
          const deleteField = ['username', 'password', 'mobile']
          for (const attr of deleteField) {
            delete userData[attr]
          }
          let isSign = false
          let lastSign = 0
          const record = await SignRecord.findByUid(userData._id)
          if (record) {
            if (
              moment(record.created).format('YYYY-MM-DD') ===
              moment().format('YYYY-MM-DD')
            ) {
              isSign = true
            }
            lastSign = record.created
          }
          userData.isSign = isSign
          userData.lastSign = lastSign
          ctx.body = {
            code: 200,
            data: userData,
            token
          }
        } else {
          ctx.body = {
            code: 404,
            msg: '用户密码不正确'
          }
        }
      } else {
        ctx.body = {
          code: 404,
          msg: '用户不存在'
        }
      }
    } else {
      ctx.body = {
        code: 404,
        msg: '图形验证码错误'
      }
    }
  }

  // 注册
  async reg (ctx) {
    const { body } = ctx.request
    const name = body.name
    const username = body.username
    const code = body.code
    const password = body.password
    const sid = body.sid
    const check = await checkCode(sid, code)
    const msg = {}
    let checkUser = true
    if (check) {
      let user = await UserModel.findOne({ username })
      if (user) {
        msg.username = '用户名已存在，请重新输入'
        checkUser = false
      }
      user = await UserModel.findOne({ name })
      if (user) {
        msg.name = '昵称已存在，请重新输入'
        checkUser = false
      }
      if (checkUser) {
        const salt = bcryptjs.genSaltSync(10)
        const pass = bcryptjs.hashSync(password, salt)
        const user = new UserModel({
          username,
          name,
          password: pass
        })
        const result = await user.save()
        ctx.body = {
          data: result,
          code: 200,
          msg: 'success'
        }
        return
      }
    } else {
      msg.code = '图形验证码有误，请重新输入'
    }
    ctx.body = {
      code: 500,
      msg
    }
  }

  // 更新
  async updatePass (ctx) {
    const { body } = ctx.request
    const check = await checkCode(body.sid, body.code)
    if (!check) {
      ctx.body = {
        code: 403,
        msg: { code: '验证码不正确' }
      }
      return
    }
    if (!body.key) {
      ctx.body = {
        code: 403,
        msg: { msg: '携带参数已失效，请重新申请发送邮件' }
      }
      return
    }
    const token = await getValue(body.key)
    if (token) {
      const obj = await getJWTPayload('Bearer ' + token)
      const salt = bcryptjs.genSaltSync(10)
      const pass = bcryptjs.hashSync(body.password, salt)
      await UserModel.updateOne(
        {
          _id: obj._id
        },
        {
          password: pass
        }
      )
      delValue(body.key)
      ctx.body = {
        code: 200,
        msg: '更新成功'
      }
    } else {
      ctx.body = {
        code: 403,
        msg: { msg: '携带参数已失效，请重新申请发送邮件' }
      }
    }
  }
}

export default new LoginController()
